package com.itmuch.demoprovider.feign;

import feign.Logger;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 内置了负载均衡
 * 整合ribbon实现的
 */
@FeignClient(name = "demo-provider",
    configuration = MyFeignClientConfiguration.class,
    fallbackFactory = DemoProviderFeignClientFallbackFactory.class
//    fallback = DemoProviderFeignClientFallback.class
)
public interface DemoProviderFeignClient {
    /**
     * 当方法被调用时，feign会构造：
     * http://demo-provider/hello-world
     * 并去请求
     *
     * @return
     */
    @GetMapping("/hello-world")
    String hello();
}

@Component
@Slf4j
class DemoProviderFeignClientFallbackFactory implements FallbackFactory<DemoProviderFeignClient> {
    @Override
    public DemoProviderFeignClient create(Throwable throwable) {
        return new DemoProviderFeignClient() {
            @Override
            public String hello() {
                log.error("feign fallback...", throwable);
                return "fallback.......";
            }
        };
    }
}

class DemoProviderFeignClientFallback implements DemoProviderFeignClient {
    @Override
    public String hello() {
        return "fallback....";
    }
}

class MyFeignClientConfiguration {
    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }
}
